/**
 * 
 */
package com.ws.framework.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.base.Charsets;
import com.ws.framework.dao.CodeDao;
import com.ws.framework.model.App;
import com.ws.framework.model.Code;
import com.ws.framework.model.Page;
import com.ws.framework.service.AppService;
import com.ws.framework.service.CodeService;
import com.ws.framework.zk.Command;
import com.ws.framework.zk.CuratorClient;

/**
 * <p>
 * </p>
 *
 * @author WSH
 */
@Service
public class CodeServiceImpl implements CodeService {

	@Autowired
	CodeDao codeDao;
	@Autowired
	AppService appService;

	@Autowired
	CuratorClient curatorClient;

	@Override
	public Page<Code> select4Page(Page<Code> page) {
		return codeDao.select4Paget(page);
	}

	@Override
	public boolean insertCode(Code code) {
		return codeDao.insert(code) > 0;
	}

	@Override
	public void updateCode(Code code) {
		codeDao.update(code);
	}

	@Override
	public void delete(long id) {
		Code code = codeDao.selectById(id);
		final App app = appService.selectAppById(code.getAppId());
		codeDao.delete(id);
		try {
			curatorClient.getClient().setData().forPath(getZkPath(app.getAppCode()),
					(Command.CODE_SOUCE_REMOVE + code.getCodeName()).getBytes(Charsets.UTF_8));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public Code selectById(long id) {
		return codeDao.selectById(id);
	}

	@Override
	public Code selectByCodeName(String codeName) {
		return codeDao.selectByCodeName(codeName);
	}

	@Override
	public boolean updateContextById(String context, long id) {
		Code code = codeDao.selectById(id);
		final App app = appService.selectAppById(code.getAppId());
		boolean result = codeDao.updateContextById(context, id) > 0;
		try {
			curatorClient.getClient().setData().forPath(getZkPath(app.getAppCode()),
					(Command.CODE_SOUCE_UPDATE + code.getCodeName()).getBytes(Charsets.UTF_8));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return result;
	}

	private String getZkPath(String code) {
		return "/app/" + code + "/dynamic";
	}

}
